package net.lovesrc.allin.biz.query;

import com.zhouzhou.fastjava.query.QueryArgs;
import com.zhouzhou.fastjava.query.QueryResult;
import net.lovesrc.allin.ExtjsQueryArgs;
import net.lovesrc.allin.Message;
import net.lovesrc.allin.controller.BaseController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
class QueryController extends BaseController {

    @RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
    public Message query(@PathVariable String id, ExtjsQueryArgs extJsArgs) throws Exception {

        if (id.contains("-stat")) {
            extJsArgs.setLimit(Integer.MAX_VALUE);
        }
        return Message.success(this.query(id, extJsArgs.args()));
    }

    @RequestMapping(value = "/lookup/{id}", method = RequestMethod.GET)
    public Message lookup(@PathVariable String id, ExtjsQueryArgs extJsArgs) throws Exception {

        extJsArgs.setLimit(Integer.MAX_VALUE);
        return Message.success(this.query(id, extJsArgs.args()).getList());
    }

    @RequestMapping(value = "/query/{id}/meta", method = RequestMethod.GET)
    public Message meta(@PathVariable String id) throws Exception {

        QueryArgs queryArgs = new QueryArgs();
        queryArgs.setLimit(1);
        QueryResult query = this.query(id, queryArgs);
        List<Map<String, Object>> rows = query.getList();
        if (rows == null || rows.isEmpty()) {
            return Message.success();
        }
        return Message.success(rows.get(0));
    }


}
